// 删除函数
export const delObjs = (objId, _this) => {
  let objIdList = [];
  let queryData = {};
  if (objId) {
    objIdList.push(objId)
  } else {
    _this.$refs.multipleTable.selection.forEach(dt => {
      objIdList.push(dt.id)
    })
  }
  queryData[_this.objID] = objIdList;
  let del_count = 0;
  objIdList.forEach(objList => {
    queryData[_this.objID] = objList;
    _this.$http.getApiFunc(_this.$http.deleteApiStatus)(_this.ListDataURL, queryData)
      .then(res => {
        if (res.data.status) {
          _this.$alert(res.data.msg, '提示', {
            confirmButtonText: '确定'
          })
        }
        del_count = del_count + 1;
        if (del_count === objIdList.length) {
          _this.objList()
        }
      })
      .catch(err => {
        console.log(err);
        _this.objList()
      })
  });

};

// 按名称搜索功能
export const inputFunc = (_this) => {
  let queryData = {
    'page': _this.currentPage,
    'size': _this.pageSize,
    'inputObjName': _this.inputObjName
  };
  if (_this.getInputData) {
    let inputDict = _this.getInputData();
    for (let key in inputDict) {
      if (inputDict[key]) {
        queryData[key] = inputDict[key]
      }
    }
  }
  _this.$http.getApiFunc(_this.$http.getApiStatus)(_this.ListDataURL, queryData)
    .then(res => {
      if (!res.error_no) {
        _this.tableData = res.data.results;
        _this.dataCount = res.data.count;
      }
    })
    .catch(err => {
      console.log(err);
    })
};

// 获取列表
export const objList = (_this) => {
  let queryData = {
    'page': _this.currentPage,
    'size': _this.pageSize
  };
  for (let key in _this.$route.query) {
    queryData[key] = _this.$route.query[key]
  }
  _this.$http.getApiFunc(_this.$http.getApiStatus)(_this.ListDataURL, queryData)
    .then(res => {
      _this.tableData = res.data.results;
      _this.dataCount = res.data.count;
    })
    .catch(err => {
      console.log(err);
    })
};

// 添加数据
export const submitForm = (_this) => {
  // 清除文件数据的字段
  if (_this.fields) {
    _this.fields.forEach(field => {
      if (!_this.ruleForm[field]) {
        delete _this.ruleForm[field]
      }
    });
  }
  // 清除不提交的字段
  if (_this.notSubmitFields) {
    _this.notSubmitFields.forEach(field => {
      delete _this.ruleForm[field]
    });
  }

  let submitData = '';
  let data = '';
  if (_this.FormDataStatus) {
    let param = new FormData();
    for (let x in _this.ruleForm) {
      param.append(x, _this.ruleForm[x])
    }
    data = param
  } else {
    data = _this.ruleForm
  }
  if (_this.$route.query[_this.EditIdStr]) {
    _this.$http.getApiFunc(_this.$http.updateApiStatus)(_this.EditUrl, _this.$route.query, data)
      .then(res => {
        if (res.data.status) {
          _this.$alert(res.data.msg, '提示', {
            confirmButtonText: '确定'
          })
        } else {
          submitData = res.data.data;
          _this.$router.push({name: _this.pushObjName});
        }
      })
      .catch(err => {
        console.log(err);
      });
  } else {
    _this.$http.getApiFunc(_this.$http.addApiStatus)(_this.EditUrl, data)
      .then(res => {
        if (res.data.status) {
          _this.$alert(res.data.msg, '提示', {
            confirmButtonText: '确定'
          })
        } else {
          submitData = res.data.data;
          _this.$router.push({name: _this.pushObjName});
        }
      })
      .catch(err => {
        console.log(err);
      });
  }
  return submitData;
};

// 获取编辑的数
export const getEditData = (_this) => {
  let status = false;
  if (_this.$route.query[_this.EditIdStr]) {
    status = true;
    _this.$http.getApiFunc(_this.$http.getApiStatus)(_this.EditUrl, _this.$route.query)
      .then(res => {
        for (let myKey in _this.ruleForm) {
          if (status) {
            let stas = true;
            if (_this.fields) {
              _this.fields.forEach(fiel => {
                if (myKey === fiel) {
                  stas = false;
                  if (res.data.results[0][myKey]) {
                    let url = _this.$http.HOST + res.data.results[0][myKey];
                    _this.$http.getApiFunc(_this.$http.getApiStatus)(url)
                      .then(res => {
                        let data = res.data;
                        if (data instanceof Object) {
                          _this.ruleForm[myKey] = JSON.stringify(data);
                        } else {
                          _this.ruleForm[myKey] = data;
                        }
                      })
                      .catch(err => {
                        console.log(err);
                      })
                  }
                }
              });
            }
            if (stas) {
              _this.ruleForm[myKey] = res.data.results[0][myKey]
            }
          }
        }
      })
      .catch(err => {
        console.log(err);
      })
  }
  return status;
};

// 获取某数据列表
export const getObjList = (_this, objURL, objList, inputObjName) => {
  // 发送啊假克丝请求
  let queryData = {
    'page': 1,
    'size': 40,
  };
  if (inputObjName instanceof Object) {
    for (let key in inputObjName) {
      if (inputObjName[key]) {
        queryData[key] = inputObjName[key]
      }
    }
  } else {
    if (inputObjName) {
      queryData['inputObjName'] = inputObjName
    }
  }
  _this.$http.getApiFunc(_this.$http.getApiStatus)(objURL, queryData)
    .then(res => {
      if (objList.length) {
        objList.splice(0, objList.length);
      }
      res.data.results.forEach(item => {
        objList.push(item)
      });
    })
    .catch(err => {
      console.log(err);
    });
};

// 获取随机字符串
export const getRandomString = (_this, queryDict)=> {
  _this.$http.getApiFunc(_this.$http.addApiStatus)(_this.$http.RandomStringURL, queryDict)
    .then(res => {
      if (res.data.status) {
        _this.$alert(res.data.msg, '提示', {
          confirmButtonText: '确定'
        })
      } else {
        _this.ruleForm.obj_key = res.data.data
      }
    })
}
;

// 密码加密
export const pwdMd = (value) => {
  if (value) {
    //首先加载node自带的加密模块
    let crypto = require('crypto');
    //使用方法
    let md5 = crypto.createHash('md5');
    let newpwd = md5.update(value).digest('hex');
    return newpwd
  }
};

// 解决url乱码问题


// 从后往前删除数组超限的元素
export const delLenghtList = (lent, value, _this) => {
  if (value.length > lent) {
    _this.$alert(`只能存在${lent}个数据`, '提示', {
      confirmButtonText: '确定'
    });
    while (value.length > lent) {
      value.pop()
    }
  }
  return value;
};

// 数组去重
export const distinct = (myArr) => {
  let arr = myArr.sort();
  let result = [arr[0]];
  for (let i = 1, len = arr.length; i < len; i++) {
    arr[i].id !== arr[i - 1].id && result.push(arr[i])
  }
  return result
};

export const unique2 = (arr) => {
  var formArr = arr.sort();
  var newArr = [formArr[0]];
  for (let i = 1; i < formArr.length; i++) {
    if (formArr[i] !== formArr[i - 1]) {
      newArr.push(formArr[i])
    }
  }
  return newArr
};


// 文件下载
export const downloads = (data, name) => {
  if (!data) {
    return
  }
  let url = window.URL.createObjectURL(new Blob([data]));
  let link = document.createElement('a');
  name = decodeURI(name);
  link.style.display = 'none';
  link.href = url;
  link.setAttribute('download', name);
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
  window.URL.revokeObjectURL(url);
};

export const downTemplate = (_this, url) => {
  let fileNames = url.split('/');
  let fileName = fileNames[fileNames.length - 1];
  _this.$http.getApiFunc(_this.$http.getApiStatus)(url)
    .then(res => {
      let data = res.data;
      // console.log(res);
      if (data instanceof Object) {
        data = JSON.stringify(data);
      }
      _this.$myTool.downloads(data, fileName)
      // export_raw(fileName,data)
    })
};


// 获取文件类型
export const getFileType = (filename) => {
  let index1 = filename.lastIndexOf(".");
  let index2 = filename.length;
  return filename.substring(index1 + 1, index2);
};

// 文件大小格式化显示
export const getRenderSize = (value) => {
  if (null == value || value == '') {
    return "0 Bytes";
  }
  var unitArr = new Array("Bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB");
  var index = 0;
  var srcsize = parseFloat(value);
  index = Math.floor(Math.log(srcsize) / Math.log(1024));
  var size = srcsize / Math.pow(1024, index);
  size = size.toFixed(2);//保留的小数位数
  return size + unitArr[index];
};
